import React, {
  useCallback, useMemo, useRef, useEffect,
} from 'react';
import { observer } from 'mobx-react-lite';
import {
  Page, Header, Breadcrumb, Content, HeaderButtons,
} from '@choerodon/master';
import {
  get,
  has as hasInject, mount,
  get as getInject,
} from '@choerodon/inject';

import {
  TextField, Icon, message, Modal as instanceModal, useModal,
} from 'choerodon-ui/pro';
import { Loading } from '@choerodon/components';
import Record from 'choerodon-ui/pro/lib/data-set/Record';
import CopyToBoard from 'react-copy-to-clipboard';
import ContentHeader from '@/routes/host-config/components/content-header';
import ContentList from '@/routes/host-config/components/content-list';
import CreateHost from '@/routes/host-config/components/create-deploy-host';
import ResourceContent from '@/routes/host-config/components/resource-content';
import EmptyPage from '@/components/empty-page';
import { SMALL } from '@/utils/getModalWidth';
import HostPermission from '@/routes/host-config/components/permission-management';
import { useHostConfigStore } from './stores';
import DragBar from '@/components/drag-bar';
import HostItemServices from '@/routes/host-config/components/content-list/components/hostItem/services';
import HostConnect from '@/routes/host-config/components/connect-host';
import DeleteCheck from '@/routes/host-config/components/content-list/components/deleteCheck';
import HostConfigApis from '@/routes/host-config/apis/DeployApis';

const HostConfig: React.FC<any> = observer((): any => {
  const Modal = useModal();
  const deployHostKey = instanceModal.key();
  const permissionKey = instanceModal.key();
  const commandModalKey = instanceModal.key();
  const {
    prefixCls,
    intlPrefix,
    formatMessage,
    refresh,
    permissionTableRefresh,
    listDs,
    mainStore,
    handleSelect,
    hasConfiguration,
    projectId,
  } = useHostConfigStore();
  const hostGroupApi = getInject('configuration-devops-api-host-group-hostGroupApi');
  const rootRef = useRef(null);
  const handleAdd = (hostId?: string) => {
    Modal.open({
      key: deployHostKey,
      title: formatMessage({ id: `${intlPrefix}.${hostId ? 'edit' : 'add'}.deploy` }),
      style: {
        width: SMALL,
      },
      drawer: true,
      children: <CreateHost
        refresh={refresh}
        hostId={hostId}
        hasConfiguration={hasConfiguration}
      />,
      okText: formatMessage({ id: hostId ? 'c7ncd.HostConfig.Save' : 'c7ncd.HostConfig.Create' }),
    });
  };
  const deleteRecord = async (id:string): Promise<boolean> => {
    try {
      const res = hasConfiguration
        ? await hostGroupApi?.deleteHost(id)
        : await HostConfigApis.getDeleteHostUrl(projectId, id);
      if (res && res.failed) {
        return false;
      }
      refresh();
      return true;
    } catch (error) {
      throw new Error(error);
    }
  };
  async function handleDelete({ id, name }:{id:string, name:string}) {
    const modalProps = {
      key: instanceModal.key(),
      title: '删除主机',
      children: <DeleteCheck
        formatMessage={formatMessage}
        hostId={id}
        hostName={name}
        projectId={projectId}
        handleDelete={() => deleteRecord(id)}
      />,
      footer: null,
    };
    Modal.open(modalProps);
  }

  useEffect(() => {
    HostItemServices.axiosGetHostDisconnect(projectId).then((res: string) => {
      mainStore.setDisConnectCommand(res);
    });
  }, []);
  /**
   * 复制按钮
   * @param text
   */
  const handleClickCopy = (text: string) => {
    message.success('复制成功');
  };
  /**
   * 断开连接
   */
  const handleDisConnect = () => {
    Modal.open({
      title: '断开连接',
      children: (
        <div>
          <p>复制以下指令至对应主机执行，来断开连接。</p>
          <TextField
            value={mainStore.getDisConnectCommand}
            disabled
            suffix={(
              <CopyToBoard text={mainStore.getDisConnectCommand} onCopy={handleClickCopy} options={{ format: 'text/plain' }}>
                <Icon style={{ cursor: 'pointer' }} type="content_copy" />
              </CopyToBoard>
              )}
            style={{
              width: '100%',
            }}
          />
        </div>
      ),
      okText: '我知道了',
      okCancel: false,
    });
  };

  const openConnectModal = (id:string) => {
    Modal.open({
      key: commandModalKey,
      title: formatMessage({ id: `${intlPrefix}.connect` }),
      children: <HostConnect hostId={id} />,
      style: { width: SMALL },
      drawer: true,
    });
  };

  const openPermissionManagement = useCallback(() => {
    if (mainStore.getSelectedMenu?.get('dataType') === 'group') {
      get('configuration-devops-routes-host-config-openAddHostGroupPermission')({ dataType: mainStore.getSelectedMenu?.get('dataType'), groupId: mainStore.getSelectedMenu?.get('id'), refresh });
      return;
    }
    Modal.open({
      key: permissionKey,
      title: '添加权限',
      style: {
        width: SMALL,
      },
      drawer: true,
      children: (
        <HostPermission
          hostData={mainStore.getSelectedHost}
          refresh={permissionTableRefresh}
          hasConfiguration={hasConfiguration}
        />
      ),
    });
  }, []);

  const getContent = useMemo(() => {
    if (listDs.status === 'loading' || !listDs) {
      return <Loading display type={get('configuration.master-global:loadingType') || 'c7n'} />;
    }
    if (listDs && !listDs.length) {
      // @ts-ignore
      return <EmptyPage title="暂无主机" describe="项目下暂无主机，请创建" />;
    }
    return (
      <div className={`${prefixCls}-content-wrap`}>
        <ContentList
          handleCreateDeployHost={handleAdd}
          handleDisConnect={handleDisConnect}
          openConnectModal={openConnectModal}
          handleDelete={(param:{id:string, name:string}) => handleDelete(param)}

        />
        <ResourceContent />
      </div>
    );
  }, [listDs, listDs.length, listDs.status]);
  const handleClick = (record:Record) => {
    const recordData = record.toData();
    mainStore.setSelectedMenu(record);
    if (recordData.dataType === 'host') {
      handleSelect(record);
    }
  };

  const handleHostGroupAdd = () => {
    if (hasInject('configuration-devops-routes-host-config-openHostGroupCreate')) {
      get('configuration-devops-routes-host-config-openHostGroupCreate')({ refresh });
    }
  };
  const renderHeader = () => {
    const arr:any = [{
      name: formatMessage({ id: 'c7ncd.environment.AddPermissions' }),
      icon: 'add',
      display: hasConfiguration ? mainStore.getSelectedMenu?.get('permissionLabel') === 'administrator' : !!listDs.length && mainStore.getSelectedHost?.permissionLabel === 'administrator',
      permissions: ['choerodon.code.project.deploy.host.ps.permission'],
      handler: openPermissionManagement,
    }, {
      icon: 'refresh',
      display: true,
      handler: refresh,
    }];
    if (hasInject('configuration-devops-routes-host-config-tree')) {
      arr.splice(0, 0, {
        name: '创建主机',
        icon: 'playlist_add',
        display: true,
        permissions: ['choerodon.code.project.deploy.host.ps.create'],
        handler: () => handleAdd(),
      }, {
        name: '创建主机组',
        icon: 'playlist_add',
        display: true,
        permissions: ['choerodon.code.project.deploy.host.ps.create'],
        handler: () => handleHostGroupAdd(),
      });
      return arr;
    }

    arr.splice(0, 0, {
      name: formatMessage({ id: 'c7ncd.environment.CreateDeploymentHost' }),
      icon: 'playlist_add',
      display: true,
      permissions: ['choerodon.code.project.deploy.host.ps.create'],
      handler: () => handleAdd(),
    });
    return arr;
  };

  return (
    <Page>
      <Header>
        <HeaderButtons
          items={renderHeader()}
          showClassName={false}
        />
      </Header>
      <Breadcrumb />
      {!hasConfiguration && <ContentHeader />}
      <Content className={`${prefixCls}-content`}>
        {hasConfiguration
          ? (
            <div ref={rootRef} className={`${prefixCls}-wrap`}>
              <DragBar
                parentRef={rootRef}
                store={mainStore}
              />
              <div className={`${prefixCls}-content-hostWrap`} style={{ width: '100%' }}>
                <div>
                  {mount('configuration-devops-routes-host-config-tree', {
                    bounds: mainStore.getNavBounds,
                    handleClick,
                    selectedValue: mainStore.getSelectedMenu,
                    fresh: mainStore.getFresh,
                    handleAdd,
                    handleDisConnect,
                    openConnectModal,
                    handleDelete,
                  })}
                </div>
                {mainStore.getSelectedMenu?.get('dataType') === 'host'
                && <div className={`${prefixCls}-main ${prefixCls}-animate`}><ResourceContent /></div>}
                {mainStore.getSelectedMenu?.get('dataType') === 'group'
                && (
                <div className={`${prefixCls}-hostContent`}>
                  {mount('configuration-devops-routes-host-config-hostContent', {
                    selectedValue: mainStore.getSelectedMenu,
                    handleAdd,
                    handleDisConnect,
                    openConnectModal,
                    handleDelete,
                    fresh: mainStore.getFresh,
                  })}
                </div>
                )}
              </div>
            </div>
          ) : getContent}
      </Content>
    </Page>
  );
});

export default HostConfig;
